package com.cj.sys.web.security;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.cj.common.orm.Page;
import com.cj.common.orm.PropertyFilter;
import com.cj.common.orm.hibernate.EntityManager;
import com.cj.common.orm.hibernate.HibernateWebUtils;
import com.cj.common.web.struts2.CRUDActionSupport;
import com.cj.common.web.struts2.Struts2Utils;
import com.cj.sys.entity.security.Authority;
import com.cj.sys.entity.security.Resource;
import com.cj.sys.service.security.AuthorityManager;
import com.cj.sys.service.security.ResourceManager;
public class AuthorityAction extends CRUDActionSupport<Authority> {
	// 权限相关属性
	private List<Resource> allResources; // 全部可选角色列表
	private List<Long> checkedResourceIds; // 页面中钩选的角色id列表
	
	@Autowired
	private ResourceManager resourceManager;

	@Autowired
	AuthorityManager authorityManager;
	@Override
	public EntityManager getEntityManager() {
		return authorityManager;
	}

	@Override
	public String input(){
		try {
			allResources = resourceManager.getAll();
			checkedResourceIds = entity.getResourceIds();
			return INPUT;			
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}
	@Override
	public String list(){
		try {
			HttpServletRequest request = Struts2Utils.getRequest();
			List<PropertyFilter> filters = HibernateWebUtils
					.buildPropertyFilters(request);
			setPage(authorityManager.search(getPage(), filters));
			return "list";			
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}

	@Override
	protected void prepareModel() throws Exception {
		if (getId() != null) {
			entity = authorityManager.get(getId());
		} else {
			entity = new Authority();
		}		
	}

	@Override
	public String save(){
		try {
			HibernateWebUtils.mergeByCheckedIds(entity.getResources(), checkedResourceIds, Resource.class);
			authorityManager.save(entity);
			addActionMessage("保存用户成功");
			return list();			
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}

	public List<Long> getCheckedResourceIds() {
		return checkedResourceIds;
	}

	public void setCheckedResourceIds(List<Long> checkedResourceIds) {
		this.checkedResourceIds = checkedResourceIds;
	}

	public List<Resource> getAllResources() {
		return allResources;
	}

}
